import { fetchUserInfo } from '@/services/user';

const Model = {
  namespace: 'user',
  state: {
    userInfo: {},
  },
  subscriptions: {
    keyEvent({ dispatch, history }: any) {
      history.listen((path: any) => {
        if (path.pathname !== '/login') {
          dispatch({
            type: 'requestUserInfo',
          });
        }
      });
    },
  },
  effects: {
    *requestUserInfo(_: any, { put, call }: any): any {
      const response = yield call(fetchUserInfo);
      yield put({
        type: 'setUserInfo',
        payload: response,
      });
    },
  },
  reducers: {
    setUserInfo(state: any, action: any) {
      return {
        ...state,
        userInfo: action.payload,
      };
    },
  },
};

export default Model;
